//引入express router
var express = require('express')
var router = express.Router();
var mongoose = require('mongoose');
 //获取数据模型
 var Goods = require('../models/goods');



//链接mongo数据库
mongoose.connect('mongodb://127.0.0.1:27017/imoocmall');

mongoose.connection.on("connected",function(){
    console.log("链接成功！");
});

mongoose.connection.on("error",function(){
    console.log("链接失败！");
});

mongoose.connection.on("disconnected",function(){
    console.log("链接断开！");
});


//查询商品列表
router.get("/",function(req,res,next){
    //排序参数
    let sort = req.param("sort");
    let page = parseInt(req.param("page"));
    let pageSize = parseInt(req.param("pageSize"));
    //价格区间
    let priceLevel = req.param("priceLevel");
    //skip 
    let skip = (page - 1)*pageSize;
    //搜索条件
    let params = {};

    if(priceLevel != "all"){
        switch (priceLevel) {
            case '0':
                priceGt=0;
                priceLte=100;
                break;
            case '1':
                priceGt=100;
                priceLte=500;
                break;
            case '2':
                priceGt=500;
                priceLte=1000;
                break;
            case '3':
                priceGt=1000;
                priceLte=5000;
                break;        
            default:
                break;
        }

        params = {
            salePrice:{
                $gt:priceGt,
                $lte:priceLte
            }
        }
    }
  

    //使用mongoose的api find进行查找所有数据 skip()跳过多少条数据
    let goodsModel = Goods.find(params).skip(skip).limit(pageSize)
    //mongoose的api sort 参数：对象{'字段',1升序-1降序}
    goodsModel.sort({'salePrice':sort})

    //加载模型获取数据
    goodsModel.exec(function (err,doc){
        if(err){
            res.json({
                status:'1',
                msg:err.message
            })
        }else{
            res.json({
                status:'0',
                msg:'',
                result:{
                    count:doc.length,
                    list:doc
                }
            })
        }
    });
});
//加入购物车
router.post("/addCart",function(req,res,next){
    //模拟登陆用户id
    var userId = "10001";
    //get取参数 req.param post取参数req.body.参数名
    var productId =req.body.productId;
    //获取数据模型
    var User = require('../models/user');
    //查找当前用户
    User.findOne({"userId":userId}, function (err,userDoc){
        if(err){
            res.json({
                status:"1",
                msg:err.message
            })
        }else{
            console.log("userDoc"+userDoc);
            if (userDoc) {
                //商品是否已存在标识
                let goodsItem = '';
                
                userDoc.cartList.forEach((item)=>{
                    if(item.productId == productId){
                        goodsItem = item;
                        item.productNum++;
                    }
                });

                if(goodsItem){
                    userDoc.save(function(err2,doc2){
                        if(err2){
                            res.json({
                                status:"1",
                                msg:err2.message
                            })
                        }else{
                            res.json({
                                status:"0",
                                msg:'',
                                result: "suc"
                            }) 
                        } 
                    })
                }else{
                    //根据前端传来的商品id查询商品信息
                    Goods.findOne({productId:productId},function(err1,doc){
                    if(err1){
                        res.json({
                            status:"1",
                            msg:err1.message
                        })
                    }else{
                        if(doc){
                            //默认添加1个商品数量 和 选中状态
                            doc.productNum = 1;
                            doc.checked = 1;
                            //加入购物车
                            userDoc.cartList.push(doc);
                            userDoc.save(function(err2,doc2){
                                if(err2){
                                    res.json({
                                        status:"1",
                                        msg:err2.message
                                    })
                                }else{
                                    res.json({
                                        status:"0",
                                        msg:'',
                                        result: "suc"
                                    }) 
                                } 
                            })
                        }
                    }
                    })  
                }
            }
        }
    })
     

});

module.exports = router;